<script setup lang="ts">
import type { UploadType } from "@@/constants/other-keys"
import type { FormInstance, FormRules, UploadUserFile } from "element-plus"
import { useRoute } from "vue-router"
import UploadFolder from "@@/components/UploadFolder/index.vue"
import { filesToZip } from "@/common/utils/fileUtils"
import { agentSupportSide, agentSupportSideMap } from "@@/constants/other-keys"
import { cloneDeep } from "lodash-es"
import { getSimEngineInfoApi } from "@/common/apis/engine-library"

interface Props {
  id: string
  sim_engine_name: string
  publishAgents: any[]
}
const route = useRoute()
const props = defineProps<Props>()
const emit = defineEmits(["update:publishAgents", "update:sim_engine_name"])

const DEFAULT_FORM_DATA: any = {
  sim_engine_id: props.id,
  sim_engine_name: "",
  sim_engine_type: "",
  sim_engine_path: "",
  sim_engine_support_side: "3",
  sim_engine_describe: "",
  sim_engine_image_id: ""
}
const detailLoading = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = ref<any>(cloneDeep(DEFAULT_FORM_DATA))
const formRules: FormRules<any> = {
  sim_engine_name: [{ required: true, trigger: "blur", message: "请输入引擎名称" }],
  sim_engine_type: [{ required: true, trigger: "change", message: "请选择引擎类型" }],
  sim_engine_path: [{ required: true, trigger: "change", message: "请选择文件" }],
  sim_engine_support_side: [{ required: true, trigger: "change", message: "请选择支持阵营" }],
  main_file: [{ required: true, trigger: "change", message: "请输入主文件名称" }]
}
const agentTypeOptions = ref<string[]>([])
const uploadType = ref<UploadType>()
const fileList = ref<UploadUserFile[]>([])
const isEdit = ref<boolean>(false)
const defaultFormData = ref<any>()


async function getParam(): Promise<FormData> {
  return new Promise(async (resolve) => {
    const params = new FormData()
    params.append("sim_engine_id", props.id)
    params.append("sim_engine_name", formData.value.sim_engine_name)
    params.append("describe", formData.value.sim_engine_describe)
    params.append("sim_engine_type", formData.value.sim_engine_type)
    params.append(`sim_engine_support_side`, formData.value.sim_engine_support_side)
    if (uploadType.value !== undefined && fileList.value.length > 0) {
      if (uploadType.value === "Folder") {
        // 压缩zip
        const files = fileList.value as File[]
        const fileBlob = await filesToZip(files)
        params.append("sim_engine_files", fileBlob, `${formData.value.sim_engine_path}.zip`)
      }
      if (uploadType.value === "File") {
        const files = fileList.value as UploadUserFile[]
        params.append("sim_engine_files", files[0].raw as Blob)
      }
    }
    resolve(params)
  })
}

// 保存
async function handleEditSave() {
  formRef.value?.validate(async (valid: boolean, fields: any) => {
    if (!valid) return console.error("表单校验不通过", fields)
    const params: FormData = await getParam()
  })
}

function getAgentInfo() {
  detailLoading.value = true
  getSimEngineInfoApi(props.id).then(({ data }) => {
    formData.value = cloneDeep(data)
  })
}

function getAgentTypeOptions() {
  // getAgentTypeOptionsApi().then(({ data }) => {
  //   agentTypeOptions.value = data.type
  // })
}
function handleEdit() {
  defaultFormData.value = cloneDeep(formData.value)
  isEdit.value = true
}
function handleEditCancel() {
  isEdit.value = false
  getAgentInfo()
}

onMounted(() => {
  nextTick(() => {
    getAgentInfo()
    getAgentTypeOptions()
  })
})

watch(
  () => fileList.value,
  () => {
    if (fileList.value.length > 0) {
      formData.value.agent_path = fileList.value[0].name
    }
  }
)
watch(
  () => fileList.value,
  () => {
    if (uploadType.value != undefined && fileList.value.length > 0) {
      if (uploadType.value == "File") {
        const files = fileList.value as UploadUserFile[]
        formData.value.agent_path = files[0].name
      }
      if (uploadType.value == "Folder") {
        // 文件夹
        const files = fileList.value as File[]
        const relativePath = files[0].webkitRelativePath
        const folderName = relativePath && relativePath.split("/")[0]
        formData.value.agent_path = folderName
      }
    } else {
      formData.value.agent_path = ""
    }
  },
  { deep: true }
)

watch(
  () => props.id,
  () => {
    nextTick(() => {
      getAgentInfo()
      getAgentTypeOptions()
    })
  }
)

onActivated(() => {
  if (props.id !== route.query.id) {
    isEdit.value = false
    getAgentInfo()
    getAgentTypeOptions()
  }
})
</script>

<template>
  <div class="version-wrapper">
    <div class="cpi-header">
      <div class="flex-center gap-1">
        <el-icon :size="18">
          <ElementPlus />
        </el-icon>
        基本信息
      </div>
      <el-space>
        <el-button v-if="isEdit" v-throttle="() => handleEditCancel()">
          取消保存
        </el-button>
        <el-button v-if="isEdit" type="primary" v-throttle="() => handleEditSave()">
          保存
        </el-button>
        <el-button v-if="!isEdit" type="primary" v-throttle="() => handleEdit()">
          编辑
        </el-button>
      </el-space>
    </div>
    <el-form v-if="isEdit" ref="formRef" :model="formData" :rules="formRules" width="600" label-width="120px" label-position="top" :close-on-click-modal="false">
      <el-row :gutter="24">
        <el-col :sm="24" :lg="24">
          <el-row :gutter="24">
            <el-col :sm="12" :lg="8">
              <el-form-item label="引擎名称" prop="sim_engine_name">
                <el-input placeholder="请输入" v-model="formData.sim_engine_name" />
              </el-form-item>
            </el-col>
            <el-col :sm="12" :lg="8">
              <el-form-item label="引擎版本" prop="sim_engine_version">
                <el-input placeholder="请输入" v-model="formData.sim_engine_version" />
              </el-form-item>
            </el-col>
            <el-col :sm="24" :lg="8">
              <el-form-item label="支持操作系统" prop="sim_engine_os">
                <el-select
                  v-model="formData.sim_engine_os" clearable placeholder="请选择"
                  popper-class="drawer-select-popper"
                >
                  <el-option
                    v-for="item in agentSupportSide" :key="item.value" :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :sm="12" :lg="8">
              <el-form-item label="环境变量" prop="environment_variables">
                <el-input placeholder="请输入" v-model="formData.environment_variables" />
              </el-form-item>
            </el-col>
            <el-col :sm="12" :lg="8">
              <el-form-item label="扩展参数" prop="extension_parameters">
                <el-input placeholder="请输入" v-model="formData.extension_parameters" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :sm="24" :md="12" :lg="24">
          <el-form-item label="引擎描述" prop="sim_engine_describe">
            <el-input v-model="formData.sim_engine_describe" type="textarea" maxlength="600" :rows="5" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form v-else class="view-form" ref="formRef" width="600" label-width="120px" label-position="top" :close-on-click-modal="false">
      <el-row :gutter="24">
        <el-col :sm="24" :lg="24">
          <el-row :gutter="24">
            <el-col :sm="24" :lg="8">
              <el-form-item label="引擎名称：" prop="sim_engine_name">
                <span :title="$getViewText(formData.sim_engine_name)">{{ $getViewText(formData.sim_engine_name) }}</span>
              </el-form-item>
            </el-col>
            <el-col :sm="24" :lg="8">
              <el-form-item label="引擎版本" prop="sim_engine_version">
                <span :title="$getViewText(formData.sim_engine_version)">{{ $getViewText(formData.sim_engine_version) }}</span>
              </el-form-item>
            </el-col>
            <el-col :sm="24" :lg="8">
              <el-form-item label="支持操作系统：" prop="sim_engine_os">
                <span :title="formData.sim_engine_os">{{ formData.sim_engine_os }}</span>
              </el-form-item>
            </el-col>
            <el-col :sm="24" :lg="8">
              <el-form-item label="环境变量：" prop="environment_variables">
                <span :title="$getViewText(formData.environment_variables)">{{ $getViewText(formData.environment_variables) }}</span>
              </el-form-item>
            </el-col>
            <el-col :sm="24" :lg="8">
              <el-form-item label="扩展参数：" prop="extension_parameters">
                <span :title="$getViewText(formData.extension_parameters)">{{ $getViewText(formData.extension_parameters) }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :sm="24" :md="12" :lg="24">
          <el-form-item label="引擎描述：" prop="sim_engine_describe" class="el-form-item_full-width">
            <span :title="$getViewText(formData.sim_engine_describe)">{{ $getViewText(formData.sim_engine_describe) }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
@import "@@/assets/styles/mixins.scss";

.version-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding-bottom: calc(var(--footer-pager) - 1px - 10px);
}
.pager-wrapper {
  padding-bottom: 0px !important;
  height: auto !important;
  width: calc(100%) !important;
}
.el-form {
  background: var(--el-bg-color);
  padding: var(--main-padding) 30px 0 30px;
  border-radius: 4px 4px 4px 4px;
  margin-bottom: var(--main-padding);
}
:deep(.view-form .el-form-item__label) {
  color: #a1accc !important;
}
:deep(.view-form .el-form-item__content) {
  & > span {
    width: 100%;
    @extend %ellipsis;
  }
}
:deep(.view-form .el-form-item_full-width .el-form-item__content) {
  overflow: hidden;
  & > span {
    display: -webkit-box; /* 使元素成为弹性盒子 */
    -webkit-box-orient: vertical; /* 设置盒子方向为垂直 */
    -webkit-line-clamp: 3; /* 限制显示的行数为 3 行 */
    overflow: hidden; /* 隐藏超出部分 */
    text-overflow: ellipsis; /* 显示省略号 */
    text-wrap: wrap;
  }
}
</style>
